<?
//Set no caching
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
date_default_timezone_set('America/Los_Angeles');

print_r($layersConfig);

function getCurrentUCSBQuarter() {
    // This Array was put together using information from
    // http://registrar.sa.ucsb.edu/calinfo.aspx
    // May need to be updated over time. (Last Updated: 06/11/2013 by Bryan Karaffa)
    // 
    // Since SUMMER doesn't have a START date specified, 
    // I used the Last day of commencement as the Summer "start date" 
   
    $ucsb_academicCalendar = array( 
        2013 => array( Winter => '2013-01-07',
                       Spring => '2013-04-01',
                       Summer => '2013-06-16',
                       Fall   => '2013-09-22',
                     ),
        2014 => array( Winter => '2014-01-06',
                       Spring => '2014-03-31',
                       Summer => '2014-06-15',
                       Fall   => '2014-09-28',
             ),
        2015 => array( Winter => '2015-01-05',
                       Spring => '2015-03-30',
                       Summer => '2015-06-15',
                       Fall   => '2015-09-28',
             ),
        2016 => array( Winter => '2016-01-04',
                       Spring => '2016-03-28',
                       Summer => '2016-06-12',
                       Fall   => '2016-09-17',
             ),
        2017 => array( Winter => '2017-01-09',
                       Spring => '2017-04-03',
                       Summer => '2017-06-18',
                       Fall   => '',
             ),
        );
    
    $today = strtotime(date("Y-m-d"));
    foreach($ucsb_academicCalendar[date("Y")] as $quarter => $start_date) {
        switch ($quarter) {
            case 'Winter':  $next_quarter = $ucsb_academicCalendar[date("Y")]['Spring']; break;
            case 'Spring':  $next_quarter = $ucsb_academicCalendar[date("Y")]['Summer']; break;
            case 'Summer':  $next_quarter = $ucsb_academicCalendar[date("Y")]['Fall']; break;
            case 'Fall':    $next_quarter = $ucsb_academicCalendar[(date("Y")+1)]['Winter']; break;
        }
        $start_date = strtotime($start_date);
        $next_quarter = strtotime($next_quarter);
        
        //print ($quarter.':<br />'.$start_date.' <= '.$today.' < '.$next_quarter.'<br />');
        if ($start_date <= $today && $today < $next_quarter) {
            return(strtolower($quarter));
        }
    }
}


function getLayerIDbyName($layer_url, $layer_name) {
    $json = file_get_contents_curl($layer_url.'?f=json');
    $MapServerJSON = json_decode($json, true);
    $r = '';
    foreach ($MapServerJSON['layers'] as $layer) {
        if ($layer['name'] == $layer_name) {
           $r = $layer['id'];
        }
    }
    return $r;
}

function getLayersConfig() {
    $configJSON = json_decode(file_get_contents_curl('http://map.geog.ucsb.edu/data/layers.json.php?layers=all'), true);
    foreach ($configJSON as $layer) {
        $layersConfig[$layer['id']]=$layer;
    }
    return $layersConfig;
}
$layersConfig = getLayersConfig();

error_reporting(E_ALL ^ E_NOTICE);
ini_set ('allow_url_fopen', 1);
function printNavigation() {
    print ('<h2>Navigation: <a href="admin.php?page=layerConfig">Layers Configuration</a> | <a href="admin.php?page=buildingPhotos">Building Photos</a> | <a href="admin.php?page=searchConfig">Search Configuration</a> | <a href="admin.php?page=imageManager">Image Manager</a> | <a href="admin.php?page=linkshortenerConfig">Link Shortener</a></h2>');
}
printNavigation();
function printMapOverLayTextbox($content) {
    $return .= '<textarea form="layerConfig" name="mapOverlay" rows=8 cols="50">'.$content.'</textarea></td></tr>';
    return $return;
}
function printZoomOnLoadDropDown($type) {
    $return = '<select name="zoomOnLoad">';
    if ($type == '2') { $campuszoom = 'selected'; }
    if ($type == '1') { $dynamic = 'selected'; }
    if ($type == '0') { $cached = 'selected'; }
    $return .= '<option value="2" '.$campuszoom.'>Campus Extent</option>';
    $return .= '<option value="1" '.$dynamic.'>Layer\'s Full Extent</option>';
    $return .= '<option value="0" '.$cached.'>Disabled</option>';

    $return .= '</select>';
    return $return;
}
function printIncludeInLayersConfigDropDown($type) {
	$return = '<select name="includeinLayersConfig">';
	if ($type == '1') { $true = 'selected'; }
	if ($type == '0') { $false = 'selected'; }
	$return .= '<option value="1" '.$true.'>Yes</option>';
	$return .= '<option value="0" '.$false.'>No</option>';
	$return .= '</select>';
	return $return;
}
function printLayerTypeDropDown($type) {
    $return = '<select name="layerType">';
    
        if ($type == 'dynamic') { $dynamic = 'selected'; }
        $return .= '<option value="dynamic" '.$dynamic.'>Dynamic</option>';
        
        if ($type == 'cached') { $cached = 'selected'; }
        $return .= '<option value="cached" '.$cached.'>Cached</option>';
        
        if ($type == 'kml') { $kml = 'selected'; }
        $return .= '<option value="kml" '.$kml.'>KML / KMZ</option>';
        
    $return .= '</select>';
    return $return;
}
function file_get_contents_curl($url) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
      curl_setopt($ch, CURLOPT_URL, $url);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
      }
function printInfoWindowConfig($infowindows) {
    $infowindows = json_decode($infowindows, true);
  
    $count = 0;
    $return='<hr />';
    //print_r($infowindows);
    if (is_array($infowindows)) {
    	foreach($infowindows as $infowindow) {
	        $return .= '<table style="vertical-align:top;">';
	        $return .= '<tr style="vertical-align:top;"><td><b><u><i>infowindow['.$count.']</i></u></b></td><td></td></tr>';
	        $return .= '<tr style="vertical-align:top;"><td>infowindow['.$count.'] Layer ID: </td><td><input type="text" form="layerConfig" name="infowindow['.$count.'][layerID]" id="infowindow'.$count.'_layerID" value="'.$infowindow['layerID'].'"></input></td></tr>';
	        $return .= '<tr style="vertical-align:top;"><td>infowindow['.$count.'] Title: </td><td><input type="text" form="layerConfig" name="infowindow['.$count.'][infowindowTitle]" value="'.$infowindow['infowindowTitle'].'"></input></td></tr>';
	        $return .= '<tr style="vertical-align:top;"><td>infowindow['.$count.'] Content: </td><td><textarea form="layerConfig" name="infowindow['.$count.'][infowindowContent]" rows=8 cols="50">'.$infowindow['infowindowContent'].'</textarea></td></tr>';
	        $return .= '</table>';
	        $return .= '<hr />';
	        $count++;
	    }
	   }
	        $return .= '<h3>New InfoWindow: </h3><br /><table style="background-color:#DDDDDD; vertical-align:top;">';
	        $return .= '<tr style="vertical-align:top;"><td><b><u><i>infowindow['.$count.']</i></u></b></td><td></td></tr>';
	        $return .= '<tr style="vertical-align:top;"><td>infowindow['.$count.'] Layer ID: </td><td><input type="text" form="layerConfig" name="infowindow['.$count.'][layerID]" id="infowindow'.$count.'_layerID"></input></td></tr>';
	        $return .= '<tr style="vertical-align:top;"><td>infowindow['.$count.'] Title: </td><td><input type="text" form="layerConfig" name="infowindow['.$count.'][infowindowTitle]"></input></td></tr>';
	        $return .= '<tr style="vertical-align:top;"><td>infowindow['.$count.'] Content: </td><td><textarea form="layerConfig" name="infowindow['.$count.'][infowindowContent]" rows=8 cols="50"></textarea></td></tr>';
	        $return .= '</table>';
	        $return .= '<hr />';
	    return $return;
    
}
function objectToArray($d) {
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
            $d = get_object_vars($d);
        }
 
        if (is_array($d)) {
            /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return array_map(__FUNCTION__, $d);
    }
    else {
        // Return array
        return $d;
    }
}
require_once('./includes/mysql.connect.php');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}
echo '<p>Connected to MySQL DB Successfully... ' . $mysqli->host_info . "\n</p>";
/*
 * Begin layersConfig Page  
 * 
 */
if (!isset($_GET['page'])) {
	$_GET['page'] = 'layerConfig';
}
if (isset($_GET['page']) && $_GET['page'] == 'linkshortenerConfig') {
    print('<iframe src="http://link.map.geog.ucsb.edu/admin/" frameborder="0" seamless="seamless" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>');
}
if (isset($_GET['page']) && $_GET['page'] == 'layerConfig') {
    if (isset($_POST['newLayer']) && $_POST['newLayer'] != '' && $_POST['newLayer'] != null) {
        $query = "INSERT INTO `icm`.`layers` (`id`, `opacity`) VALUES ('".$_POST['newLayer']."', '1')";
        if ($result = $mysqli->query($query)) {
            header('Location: /admin.php?page=layerConfig&configLayer='.$_POST['newLayer']);
        }
    }
    if (isset($_GET['removeLayer']) && $_GET['removeLayer'] != '' && $_GET['removeLayer'] != null) {
        $query = "DELETE FROM `icm`.`layers` WHERE `layers`.`id` = '".$_GET['removeLayer']."'";
        if ($result = $mysqli->query($query)) {
            header('Location: /admin.php?layerDeleted=1');
        }
    }
    if (isset($_GET['configLayer'])) {
        if (isset($_POST) && ($_POST['layerId'] != NULL)) {
            $layer['id'] = $_POST['layerId'];
            $layer['url'] = $_POST['layerURL'];
            $layer['type'] = $_POST['layerType'];
            $infowindows = $_POST['infowindow'];
            $layer['zoomOnLoad'] = $_POST['zoomOnLoad'];
            $layer['includeinLayersConfig'] = $_POST['includeinLayersConfig'];
            $layer['mapOverlay'] = $mysqli->real_escape_string($_POST['mapOverlay']);
            $count = 0;
            if ($infowindows != null) {
            	foreach ($infowindows as $infowindow) {
                if ($infowindow['layerID'] == NULL && $infowindow['infowindowTitle'] == NULL && $infowindow['infowindowContent'] == NULL) {
                    //$msgs .= 'Removed infowindow['.$count.']<br />';
                }
                else {
                    $infowindow['infowindowTitle'] = $mysqli->real_escape_string($infowindow['infowindowTitle']);
                    $infowindow['infowindowContent'] = $mysqli->real_escape_string($infowindow['infowindowContent']);
                    $i[] = $infowindow;
				}
                $count++;    
            	}
				if (is_array($i)) {
					$layer['infowindow'] = json_encode(array_filter($i));
					$layer['infowindow'] = "'".$layer['infowindow']."'";
					
				}
				else {
					$layer['infowindow'] = $mysqli->real_escape_string('NULL');
				}
			}

            $query = "UPDATE `icm`.`layers` SET `id`='".$layer['id']."', `url` = '".$layer['url']."', `type`='".$layer['type']."',`infowindow` = ".$layer['infowindow'].",`zoomOnLoad` = '".$layer['zoomOnLoad']."',`mapOverlay` = '".$layer['mapOverlay']."', `includeinLayersConfig` = '".$layer['includeinLayersConfig']."' WHERE `layers`.`id` = '".$_GET['configLayer']."';";
			$msgs .= 'Query: '.$query.'.';			
            if ($result = $mysqli->query($query)) {
                print('<div style="width: 33%; background-color: green; position:fixed; bottom:0px; right: 10px; padding: 20px;"> Layer Updated! <br /><span style="font-size:60%"> '.$msgs.'</span></div>');                  
            }
            else {
                print('<div style="width: 33%; background-color: red; position:fixed; bottom:0px; right: 10px; padding: 20px;"> Error! <br /><span style="font-size:60%"> '.$msgs.'</span></div>');
            }
        }
        print('<h3>Edit Layer Configuration</h3>');
        $query = "SELECT * FROM `layers` WHERE `id` = '".$_GET['configLayer']."' LIMIT 0,1";
        if ($result = $mysqli->query($query)) {
            print ('<SCRIPT type="text/javascript">
                    function confirmDelete(id) {
                        var r=confirm("Confirm you want to delete the "+id+" layer?");
                        if (r==true) {
                          var r2=confirm("Are you positive you want to delete "+id+" layer");
                          if (r2==true) {
                            window.location = "/admin.php?page=layerConfig&removeLayer="+id;
                          }
                        }
                    }
                    </SCRIPT>');
            print('<form id="layerConfig" action="'.$_SERVER['REQUEST_URI'].'" method="post"><table>');
            //print('<tr style="text-align:center; font-weight:bold;"><td>unique id</td><td>url</td><td>infowindow(s)?</td></tr>');
            for ($i=0; $i < ($result->num_rows); $i++) {
                $row = $result->fetch_array(MYSQLI_ASSOC);
                print('<tr><td>Layer ID: </td><td><input type="text" name="layerId" value="'.$row['id'].'" /></td></tr>');
                print('<tr><td>Layer URL: </td><td><input type="text" name="layerURL" value="'.$row['url'].'" style="width:400px" /></td></tr>');
                print('<tr><td>Layer Type: </td><td>'.printLayerTypeDropDown($row['type']).'</td></tr>');
                print('<tr><td>Include in default layers.json config: </td><td>'.printIncludeInLayersConfigDropDown($row['includeinLayersConfig']).'</td></tr>');
                print('<tr><td>Zoom to Extent onLoad?: </td><td>'.printZoomOnLoadDropDown($row['zoomOnLoad']).' </td></tr>');
                print('<tr><td style="vertical-align:top;">Map Overlay HTML: </td><td>'.printMapOverLayTextbox($row['mapOverlay']).' </td></tr>');
                print('<tr><td style="vertical-align:top;">InfoWindow(s): </td><td>'.printInfoWindowConfig($row['infowindow']).'</td></tr>');
                print('</table><button type="submit">Update Layer</button></form>');
                print('<br /><br /><hr /><br /><br /><h2>Delete Layer<br /><button onclick=\'confirmDelete("'.$row['id'].'")\'>Delete Layer (CAUTION!!)</button>');
            }
        //print(json_encode($row));
         /* free result set */
        $result->close();
        }
    }
    else {
        print('<h2>Layer Configuration</h2>');
        print('<h4><a href="/admin.php?page=getJSON">[ View Output Layers Config (JSON) ]</a></h4>');
        print('<form id="newLayer" action="'.$_SERVER['REQUEST_URI'].'" method="post">');
        print('Add new layer: <input type="text" name="newLayer"><button type="submit">Add Layer</button>');
        print('</form>');
        $query = "SELECT * FROM `layers`";
        if ($result = $mysqli->query($query)) {
            printf("Select returned %d rows.\n", $result->num_rows);
            printf("(".$query.")<br /><br />");
            print('<table>');
            print('<tr style="text-align:center; font-weight:bold;"><td>unique id</td><td>url</td><td>zoomOnLoad?</td><td>infowindow(s)?</td></tr>');
            for ($i=0; $i < ($result->num_rows); $i++) {
                $row = $result->fetch_array(MYSQLI_ASSOC);
                if (is_int($i /2)) { $rowColor = '#CCCCCC'; }
                if (!is_int($i /2)) { $rowColor = 'white'; }
                print('<tr style="background-color:'.$rowColor.'">');
                //print_r($row);
                print('<td><a href="/admin.php?page=layerConfig&configLayer='.$row['id'].'">'.$row['id'].'</a></td>');
                print('<td>'.$row['url'].'</td>');
                print('<td style="text-align:center;">');
                if ($row['zoomOnLoad'] == 1) {
                    print('Yes');
                }
                else {
                    print('&nbsp;');
                }
                print('<td style="text-align:center;">');
                if ($row['infowindow'] != NULL) {
                    print('Yes');
                }
                else {
                    print('&nbsp;');
                }
                print('</td>');
                print('</tr>');   
            }
         /* free result set */
        $result->close();
        print('</table>');
        }
    }
}
if (isset($_GET['page']) && $_GET['page'] == 'getJSON') {
        print('<h2>Layer Configuration</h2>');
        $query = "SELECT * FROM `layers`";
        if ($result = $mysqli->query($query)) {
            for ($i=0; $i < ($result->num_rows); $i++) {
                $row = $result->fetch_array(MYSQLI_ASSOC);
                $layersJSON[$i] = $row;               
            }
        }
        $layersJSON = json_encode($layersJSON);
        print(htmlspecialchars($layersJSON));             
         /* free result set */
        $result->close();
}
function fileExists($path){
    return (@fopen($path,"r")==true);
}
if (isset($_GET['page']) && $_GET['page'] == 'buildingPhotos') {
	
	$jsonURL = 'http://128.111.104.32:8080/arcgis/rest/services/icm/icmRoomsAndBuildings/MapServer/1/query?where=bl_num>0&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=bl_num%2Cb_name&returnGeometry=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=bl_num+ASC&groupByFieldsForStatistics=bl_num&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json';
	
	$json = json_decode(file_get_contents($jsonURL), true);
	print ('<table><tr><td>building #</td><td>picture</td><td>building name</td><td>actions</tr>');
	$i = 0;
	foreach ($json['features'] as $building) {
        if (is_int($i /2)) { $rowColor = '#CCCCCC'; }
        if (!is_int($i /2)) { $rowColor = 'white'; }
        
        $file = '/images/i/bldg_'.$building['attributes']['bl_num'].'/thumb/?ref=admincp';
        //$thumbfile = 'http://mapdev.geog.ucsb.edu/images/building_photos/bynumber_Thumbs/'.$building['attributes']['b_number'].'_1.jpg';
        $thumbfile = $file;
        print('<tr style="margin:10px;background-color:'.$rowColor.'"><td>'.$building['attributes']['bl_num'].'</td><td><a href="'.$file.'" target="_blank"><img src="'.$thumbfile.'" style="max-width:150px; max-height:150px;"></img></a></td><td>'.$building['attributes']['b_name'].'</td><td><a href="/admin.php?page=editPhoto&photo_id=bldg_'.$building['attributes']['bl_num'].'">Edit</a> | Delete</td></tr>');
        $i++;
        
	}
	print('</table>');
}
if (isset($_GET['page']) && $_GET['page'] == 'imageManager') {
    if (isset($_GET['action']) && isset($_GET['photo_id']) && $_GET['action'] == 'delete') {
        $query = "DELETE FROM `images` WHERE `image_id` = '".$_GET['photo_id']."'";
        if ($result = $mysqli->query($query)) {
            header('Location: /admin.php?page=imageManager&imageRemoved=1');
        }
    }
    elseif (isset($_GET['imageRemoved']) && $_GET['imageRemoved'] == 1) {
        print('<div style="width: 33%; background-color: green; padding: 20px;">Image Successfully Deleted!</div>');                  
    }
    
        function showImageList($results) {
            //print '<table><tr><td><h2>Image</h2></td><td><h2>Date Added</h2></td><td><h2>Actions</h2></td></tr>';
            //foreach ($results as $img) {
            //    print('<tr><td>'.$img['image_id'].'</td><td>'.$img['date_added'].'</td><td>Edit | Delete</td></tr>');
            //}
            //print '</table>';
            $i=0;
            foreach ($results as $img) {
               if (is_int($i /2)) { $rowColor = '#CCCCCC'; }
               if (!is_int($i /2)) { $rowColor = 'white'; }
               print'<div style="text-align:center; float:left; height:150px; margin:2px; padding:2px;background-color:'.$rowColor.'">';
               print('<a href="/admin.php?page=editPhoto&photo_id='.$img['image_id'].'"><img src="/images/i/'.$img['image_id'].'/thumb/?ref=admincp" style="max-height:100px" alt="'.$img['image_id'].'"></img><br />'.$img['image_id'].'</a><br />'.$img['date_added'].'');
               print('</div>');
               $i++;
            }
            
        }
    
        $searchText = explode(' ',$_POST['searchText']);
        $query = "SELECT DISTINCT `image_id`,`date_added` FROM `images` WHERE `image_id` NOT LIKE 'bldg_%' GROUP BY `image_id` ORDER BY `image_id` ASC";
        
        
        print($query.'<br />');
        if ($result = $mysqli->query($query)) {
            printf("<p>Select returned %d rows.</p>", $result->num_rows);
            for ($i=0; $i < ($result->num_rows); $i++) {
                $row = $result->fetch_array(MYSQLI_ASSOC);
                $results[] = $row;
            }
            
        }
        else {
            print(mysqli_error($mysqli));
        } 
         /* free result set */
        $result->close();
        
                print ('
                <script type="text/javascript">
                function checkForm(f) {
                    if (f.elements["image_id"].value == "" || f.elements["image"].value == "") {
                        alert("You have not specified a unique image_id or filename.");
                        return false;
                    }
                    else {
                        f.submit();
                        return false;
                    }
                }
                </script>
                <form action="/admin.php?page=editPhoto&action=newphoto" method="post" enctype="multipart/form-data" onSubmit="return checkForm(this); return false;">
                    <div>
                          <hr />
                          <h4>Upload New Image<u><i><b>'.$_GET['photo_id'].'</b></i></u>:</h4>
                          <label>New Image ID:</label>
                          <input type="text" name="image_id"/>
                          <input type="file" name="image" />
                          <input name="submit" type="submit" value="Upload">
                    </div>
                </form><hr/>');
        showImageList($results);
}
if (isset($_GET['page']) && $_GET['page'] == 'editPhoto') {
if ($_POST && !empty($_FILES)) {
        function resizeImage($path, $width, $height) {           

            $image = new Resize_Image;

            $image->new_width = $width;
            $image->new_height = $height;

            $image->image_to_resize = $path; // Full Path to the file

            $image->ratio = true; // Keep Aspect Ratio?

            // Name of the new image (optional) - If it's not set a new will be added automatically

            $image->new_image_name = 'uploaded_image';

            /* Path where the new image should be saved. If it's not set the script will output the image without saving it */

            $image->save_folder = '/web/icm/public_html/images/';

            $process = $image->resize();

            if($process['result'] && $image->save_folder)
            {
            //echo 'The new image ('.$process['new_file_path'].') has been saved.';
                return $process;
                //print_r($process);
            }
            else { return false; }
            
        }    
    
        //START FORM SCRIPT
	$formOk = true;

	//Assign Variables
	$path = $_FILES['image']['tmp_name'];
	$name = $_FILES['image']['name'];
	$size = $_FILES['image']['size'];
	$type = $_FILES['image']['type'];

	if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
		$formOk = false;
		echo "Error: Error in uploading file. Please try again.";
	}

	//check file extension
	if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/gif'))) {
		$formOk = false;
		echo "Error: Unsupported file extension. Supported extensions are JPG / PNG / GIF.";
	}
	// check for file size.
	//if ($formOk && filesize($path) > 5000000) {
	//	$formOk = false;
	//	echo "Error: File size must be less than 5000 KB.";
	//}
	if ($formOk) {
                include_once('includes/class.Resize_Image.php');
		// read file contents
		$content = file_get_contents($path);


		//connect to mysql database
		if ($mysqli) {                     
                    $isize = getimagesize($path);
                    print('Path: '.$path."<br />");
                    $imagesize['width'] = $isize[0];
                    $imagesize['height'] = $isize[1];
                    //print_r($imagesize);

                    if ($imagesize['width'] > 150 || $imagesize['height'] > 150) {
                        print ('Image Larger than Thumbnail.');
                        //Run this because the image size is > the thumb size

                        $result = resizeImage($path, 150, 150); // resizes the image and saves the resized image to images/uploaded_image.jpg/gif/png
                        print_r($result); // debugging
                        $thumb = file_get_contents($result['new_file_path']); // puts the contents of file into string
                        unlink($result['new_file_path']); // Deletes the temporary file
                    }
                    else { //If the Original is < 150x150, use the original image.
                        $thumb = file_get_contents($path);
                    }
                    if ($imagesize['width'] > 1024 || $imagesize['height'] > 768) {
                        print ('Image Larger than resized.');
                        $result = resizeImage($path, 1024, 768);
                        print_r($result);
                        $resized = file_get_contents($result['new_file_path']);
                        unlink($result['new_file_path']);
                    }
                    else { //If the Original is < 1024x768, use the original image.
                        $resized = file_get_contents($path);
                    } 
                        
                        
                        
                        
                        //Clean everything before we store it in MySQL
                        $content = mysqli_real_escape_string($mysqli, $content);
                        $resized = mysqli_real_escape_string($mysqli, $resized);
                        $thumb = mysqli_real_escape_string($mysqli, $thumb);
                        $name = mysqli_real_escape_string($mysqli, $name);
                        $image_id = mysqli_real_escape_string($mysqli, $_POST['image_id']);
                        
                        
                        $sql = "insert into images (image_id, name, size, type, content, resized, thumb) values ('{$image_id}', '{$name}', '{$size}', '{$type}', '{$content}', '{$resized}', '{$thumb}')";
                        //print($sql);
			if (mysqli_query($mysqli, $sql)) {
				$uploadOk = true;
				//$imageId = mysqli_insert_id($mysqli);
			} else {
				echo "Error: Could not save the data to mysql database. Please try again.\nError: \n";
                                echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli). "\n";
			}

		} else {
			echo "Error: Could not connect to mysql database. Please try again.";
		}
	}
}    
    
    
    
    
    if (isset($_GET['photo_id']) || $_GET['action'] == 'newphoto') {
        $photo_id = $_GET['photo_id'];       
       
        if (!empty($uploadOk)) {
            // Image Uploaded Successfully!
            // Comment the line below to prevent the editPhoto to forward the page upon upload (for debugging purposes).
            if (isset($_GET['action']) && $_GET['action'] == 'newphoto') {
                $photo_id = $_POST['image_id'];
            }
            print ('<script type="text/javascript"> window.location= "/admin.php?page=editPhoto&photo_id='.$photo_id.'&success=true" </script>');
        }
        if ($_GET['success'] == true) {
            print ('<div style="font-color:green;"><h3>Image Uploaded Successfully!</h3>If you do not see the image below, try refreshing the page (CTRL+F5 will reload the page from scratch)</div><hr>');
        }
        print ('<SCRIPT type="text/javascript">
        function confirmDelete(id) {
            var r=confirm("Confirm you want to delete the "+id+" image?\n\nNOTE: This will delete ALL versions of the image INCLUDING previously uploaded versions.");
            if (r==true) {
              var r2=confirm("Are you positive you want to delete the "+id+" image");
              if (r2==true) {
                window.location = "/admin.php?page=imageManager&action=delete&photo_id="+id;
              }
            }
        }
        </SCRIPT>');
        print ('<form action="/admin.php?page=editPhoto&photo_id='.$photo_id.'" method="post" enctype="multipart/form-data" >
                    <div>
                          <h3>Upload image for <u><i><b>'.$photo_id.'</b></i></u>:</h3>
                    </div>
                    <div>
                          <label>Image</label>
                          <input type="hidden" name="image_id" value="'.$photo_id.'"/>
                          <input type="file" name="image" />
                          <input name="submit" type="submit" value="Upload">
                    </div><br />
                    <div>Current Images:<br />
                        Thumb: <img src="/images/i/'.$photo_id.'/thumb/?ref=admincp" border="0"></img><hr />
                        Resized: <img src="/images/i/'.$photo_id.'/resized/?ref=admincp" border="0"></img><hr />
                        Original: <img src="/images/i/'.$photo_id.'/?ref=admincp" border="0" style="max-width:100%"></img>
                    </div>
                  </form>');
        print('<br /><br /><hr /><br /><br /><h2>Delete Image<br /><button onclick=\'confirmDelete("'.$photo_id.'")\'>Delete Image (CAUTION!!)</button>');
    }
    else {
        print('Error: Building number not specified.');
    }
}
/////////////////////////////////////////////////////////////
////    
////                Search Admin Module                  ////
////
/////////////////////////////////////////////////////////////
if (isset($_GET['page']) && $_GET['page'] == 'searchConfig') {
    print('<h2>Search Configuration</h2>');
    print('<h3><a href="/admin.php?page=searchConfig&searchConfig=buildings">Buildings</a> | <a href="/admin.php?page=searchConfig&searchConfig=classes">Classes</a> | <a href="/admin.php?page=searchConfig&searchConfig=rooms">Rooms</a> | <a href="/admin.php?page=searchConfig&searchConfig=people">People</a> | <a href="admin.php?page=searchConfig&searchConfig=campusServices">Campus Services</a> | <a href="admin.php?page=searchConfig&searchConfig=recreationAreas">Recreation Areas</a> | <a href="admin.php?page=searchConfig&searchConfig=foodEstablishments">Food Establishments</a> | <a href="admin.php?page=searchConfig&searchConfig=parking">Parking</a></h2>');
    print ('<SCRIPT type="text/javascript">
function confirmDelete() {
  var r=confirm("Replace the current searchable features with the values on the page?\n\nNOTE: This will delete ALL previous values and insert only the values on this page.");
  if (r==true) {
    var r2=confirm("Double Checking:\n\nAre you positive you want to replace the current searchable features with the values on the page? CANNOT BE UNDONE!");
    if (r2==true) {
    window.location = "'.$_SERVER['REQUEST_URI'].'&updateDB=yes";
    }
  }
}
</SCRIPT>
<hr /><a href="#" onClick="confirmDelete()">Update/Replace searchableFeatures DB with features below (CAREFUL)</a><hr />
            ');
   
    /// SEARCH TEST
    //print(' <form action="/admin.php?page=searchConfig" method="POST">
    //        <input type="search" name="searchText">
    //         <input type="submit" value="Search">
    //    </form>');
    print('<pre>');
    if(isset($_POST['searchText'])) {
        //            
        // Method 1: LIKE %...%
        //    
        //$searchText = explode(' ',$_POST['searchText']);
        //$WHERE = '';
        //foreach($searchText as $string) {
        //    $WHERE .= "LOWER(`tags`) LIKE  LOWER('%".$string."%') OR ";
        //}
        //$WHERE = substr($WHERE,0,-3);
        //$query = "SELECT * FROM  `searchablefeatures` WHERE ".$WHERE;
        
        //
        // Method 2: FULLTEXT Search
        //
        $searchText = explode(' ',$_POST['searchText']);
        $query = "SELECT *, MATCH (`tags`) AGAINST ('".$_POST['searchText']."' IN NATURAL LANGUAGE MODE) AS searchScore FROM `searchablefeatures` WHERE MATCH (`tags`) AGAINST ('%".$_POST['searchText']."%' IN NATURAL LANGUAGE MODE)";
        
        
        print($query.'<br />');
        if ($result = $mysqli->query($query)) {
            printf("Select returned %d rows.\n", $result->num_rows);
            for ($i=0; $i < ($result->num_rows); $i++) {
                $row = $result->fetch_array(MYSQLI_ASSOC);
                print_r($row);             
            }
        }
        else {
            print(mysqli_error($mysqli));
        }
         /* free result set */
        $result->close();        
    }
            ////END SEARCH TEST
    if($_GET['searchConfig'] == 'buildings') {
        
            
            $buildingsJSON = file_get_contents('http://128.111.104.32:8080/arcgis/rest/services/icm/icmRoomsAndBuildings/MapServer/1/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=bl_num&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json');
            $buildingsJSON = json_decode($buildingsJSON);
           //print_r($buildingsJSON); // DEBUGGER
           $count = 0;
            foreach($buildingsJSON->features as $building) {
                //print_r($building); // DEBUGGER     
                $buildings[$count]['number'] = $building->attributes->bl_num;
                $buildings[$count]['name'] = $building->attributes->b_name;
                $buildings[$count]['departments'] = $building->attributes->department;
                $buildings[$count]['abbreviation'] = $building->attributes->b_abbreb;
                $buildings[$count]['geometry'] = str_replace('"', "", json_encode($building->geometry));
                $count++;
            }
            //print_r($buildings); //DEBUGGER
            foreach($buildings as $building) {
                $tags = '';
                //print_r($building);
                if ($building['name'] != ' ' && $building['name'] != '' && $building['name'] != null) {
                    $tags .= $building['name'].' '; 
                }
                else {
                    $building['name'] = 'Building '.$building['number'];
                }
        
                if ($building['number'] != '') {
                    $tags .= 'building '.$building['number'].' '; 
                }
                if ($building['abbreviation'] != '') {
                    $tags .= $building['abbreviation'].' '; 
                }
                $tags = implode (' ', array_unique(explode(' ',$tags)));
                $building['tags'] = $tags;
                $output[]=$building;
            }
            
            // Clean and Prep the Database for insertion.
            if ($_GET['updateDB'] == 'yes') {
                $query = "DELETE FROM `searchablefeatures` WHERE `searchablefeatures`.`category` = 'building';";
                print($query.'<br />');
                if ($result = $mysqli->query($query)) {
                    print('Building features successfully cleared!<br />');
                }
                else {
                    print(mysqli_error($mysqli));
                }
                /* free result set */
                //$result->close(); 
            }
            // Setup the SQL statement with all the values.
            foreach ($output as $building) {
                if ($_GET['updateDB'] == 'yes') {                  
                    $valuesSQL[]="('building', '".mysqli_escape_string($mysqli, $building['name'])."', '".mysqli_escape_string($mysqli, $building['tags'])."', '".mysqli_escape_string($mysqli, $building['name'])."', '".$building['geometry']."')";
                }
                else {
                    print('building|'.$building['name'].'|'.$building['tags'].'|'.$building['name'].'|'.$building['geometry'].'<br />');
                }
            }
            // Insert values into Database.
            if ($_GET['updateDB'] == 'yes') {
                $values = implode(",\n", $valuesSQL);
                $query = "INSERT INTO `icm`.`searchablefeatures` (`category`, `label`, `tags`, `location`, `geometry`) VALUES ".$values.";";
                print ($query."\n");
                if ($result = $mysqli->query($query)) {
                    print("Insert Executed Successfully.");
                }
            }
            
            
    } // End Buildings Search Configuration
    if ($_GET['searchConfig'] == 'classes') {
        
        function getRoomGeometry($building,$room) {
            //$prefixBuildings and $prefixRooms are temporary fixes to an ultimately larger organization issue
            //Depending on Whether the layers are joined and where they are referenced from,
            //The attribute name can change..... To fix this issue we check the MapService URL (http://128.111.104.32:8080/arcgis/rest/services/icm/icmRoomsAndBuildings/MapServer/0)
            //The RoomsLayer is Joined to the buildings layer and there should a fairly obvious "prefix" for each layers attributes..          
            //
            //Ultimately, once we decide on a data model and organize our data we shouldn't need to use this value anymore.
            $prefixBuildings = 'Buildings.';
            $prefixRooms = 'RoomsAllFloors.';
            
            //print('Building: '.$building.' | Room: '.$room.'<br />');
            //Get the building number from the mapserver using the building abbreviation
            //$buildingquery = 'http://128.111.104.32:8080/arcgis/rest/services/icm/icmRoomsAndBuildings/MapServer/1/query?where=b_abbreb+LIKE+%27%25'.urlencode($building).'%25%27&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json';

            
            $buildingquery = 'http://map.geog.ucsb.edu:8080/arcgis/rest/services/icm/icmRoomsAndBuildings/MapServer/1/query?where=b_abbreb+LIKE+%27%25'.urlencode($building).'%25%27&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=bl_num&returnGeometry=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json';
            //print('BQ:'.$buildingquery.'<br />');
            $buildingJSON = file_get_contents($buildingquery);
            $buildingJSON = json_decode($buildingJSON);
            $bNumber = $buildingJSON->features[0]->attributes->bl_num;
            //print('Building Number from MapService: '.$bNumber.'<br />');
            
            //Get the geometry using the building number and room number and querying the RoomsAllFloors Mapservice.
            if (($bNumber == null || $bNumber == 'null') && is_integer($building)) {
                $bNumber = $building;
            }
            $roomquery = 'http://map.geog.ucsb.edu:8080/arcgis/rest/services/icm/icmRoomsAndBuildings/MapServer/0/query?where='.$prefixBuildings.'bl_num+%3D+'.urlencode($bNumber).'+AND+%28'.$prefixRooms.'rm_num+LIKE+%27%25'.urlencode($room).'%25%27+OR+'.$prefixRooms.'alt_identifiers+LIKE+%27%25'.urlencode($room).'%25%27%29&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json';
            
            //print('RQ: '.$roomquery.'<br />');
            $roomJSON = file_get_contents($roomquery);
            $roomJSON = json_decode($roomJSON);
            
            //print_r($buildingJSON);
            //print_r($roomJSON);
            return(json_encode($roomJSON->features[0]->geometry));
        }

        
        
        
           $table = date("Y")."-".getCurrentUCSBQuarter()."-all";
           print('Current Table: '.$table.' [Detected from current date+UCSB Schedule]<br />');
           if (isset($_GET['db'])) {
               $table = $_GET['db'];
           }
           print('<h4>Classes & Sections <a href="/admin.php?page=searchConfig&searchConfig=classes&showall=1">[Show All]</a> (may take some time to load)</h4>');
           print("<p>Set \$_GET[db] to the table you want. [DO NOT EDIT IF YOU DON'T KNOW WHAT YOU'RE DOING]<br />(Default Table is detected based on the date and UCSB Schedule).<br />( Example: <a href='/admin.php?page=searchConfig&searchConfig=classes&db=".$table."'>/admin.php?page=searchConfig&searchConfig=classes<b></u>&db=".$table."</u></b></a> )</p>");
           
           
           
           
            $query = "SELECT * FROM `".$table."` LIMIT 0,30";
            if($_GET['showall'] == 1 || $_GET['updateDB'] == 'yes')  {
                $query = "SELECT * FROM `".$table."`";
            }
            if ($result = $mysqli->query($query)) {
                print('<pre>');
                $output='';
                for ($i=0; $i < ($result->num_rows); $i++) {
                    $row = $result->fetch_array(MYSQLI_ASSOC);
                    //print_r($row);
                    $row['primaryTitle'] = trim($row['primaryTitle'] );
                    $row['courseTitle'] = trim($row['courseTitle'] );
                    $row['fullTitle'] = trim($row['fullTitle'] );
                    $row['instructor'] = trim($row['instructor'] );
                    $row['bldg'] = trim($row['bldg']);
                    $row['room'] = trim($row['room']);
                    $row['location'] = trim($row['location']);
                    $row['enrollCode'] = trim($row['enrollCode']);
                    $classType='class';
                    if($row['primaryTitle'] == '' || $row['primaryTitle'] == null || $row['primaryTitle'] == ' ') {
                         $label = $row['courseTitle'].' Section';
}
                    else {
                         $label = $row['primaryTitle'].' ('.$row['courseTitle'].')';
                    }
                    $tags = $row['courseTitle'].' '.str_replace(' ','',$row['courseTitle']).' '.$row['instructor'].' '.$row['bldg'].' '.$row['room'].' '.$row['location'].' '.$row['enrollCode'];
                    if ($row['fullTitle'] != '' && $row['fullTitle'] != ' ' && $row['fullTitle'] != null) {
                        $tags .= ' '.$row['fullTitle'];
                    }
                    if ($row['primaryTitle'] != '' && $row['primaryTitle'] != ' ' && $row['primaryTitle'] != null) {
                        $tags .= ' '.$row['primaryTitle'];
                        $tags .= ' class';
                    }
                    else {
                        $tags.= ' section';
                        $classType = 'section';
                    }
                    $tags = str_replace("\r\n",'',trim($tags));
                    $tags = str_replace("  ",' ',$tags);
                    $tags = str_replace("  ",' ',$tags);
                    $tags = str_replace("  ",' ',$tags);
                    $tags = str_replace("  ",' ',$tags);
                    $tags = str_replace("  ",' ',$tags);
                    $tags = str_replace("  ",' ',$tags);
                    $tags = str_replace("  ",' ',$tags);
                    $tags = implode (' ', array_unique(explode(' ',$tags)));
                    //print_r($row);
                    
                    $geometry = getRoomGeometry($row['bldg'],$row['room']);
                    $geometry = str_replace('"', "", $geometry);
                    

                    //$output[].='class|'.$label.'|'.$tags.'|'.$geometry.'<br />';
                    $array=array('category' => $classType,'label' => $label, 'tags' => $tags, 'location' => $row['bldg'].' '.$row['room'], 'geometry' => $geometry);
                    //print_r($array);
                    $output[] = $array;
                    //print($classType.'|'.$label.'|'.$tags.'|'.$row['bldg'].' '.$row['room'].'|'.$geometry.'<br />');
                }
             /* free result set */
            $result->close();

            // Clean and Prep the Database for insertion.
            if ($_GET['updateDB'] == 'yes') {
                $query = "DELETE FROM `searchablefeatures` WHERE `searchablefeatures`.`category` = 'class' OR `searchablefeatures`.`category` = 'section';";
                print($query.'<br />');
                if ($result = $mysqli->query($query)) {
                    print('Class / Section features successfully cleared!<br />');
                }
                else {
                    print(mysqli_error($mysqli));
                }
                /* free result set */
                //$result->close(); 
            }
            // Setup the SQL statement with all the values.
            foreach ($output as $building) {
                if ($_GET['updateDB'] == 'yes') {                  
                    //print_r($building);
                    $valuesSQL[]="('".mysqli_escape_string($mysqli, $building['category'])."', '".mysqli_escape_string($mysqli, $building['label'])."', '".mysqli_escape_string($mysqli, $building['tags'])."', '".mysqli_escape_string($mysqli, $building['location'])."', '".$building['geometry']."')";
                }
                else {
                    //print_r($building);
                    print($building['category'].'|'.$building['label'].'|'.$building['tags'].'|'.$building['location'].'|'.$building['geometry'].'<br />');
                }
            }
            // Insert values into Database.
            if ($_GET['updateDB'] == 'yes') {
                $values = implode(",\n", $valuesSQL);
                $query = "INSERT INTO `icm`.`searchablefeatures` (`category`, `label`, `tags`, `location`, `geometry`) VALUES ".$values.";";
                print ($query."\n");
                if ($result = $mysqli->query($query)) {
                    print("Insert Executed Successfully.");
                }
            }
        }
            //print_r($output);
     //       print(implode('', $output));
    }
    if ($_GET['searchConfig'] == 'rooms') {
        print('<pre>');
        //Get the rooms by querying the Rooms MapServer REST API 
        $roomsJSON = file_get_contents('http://128.111.104.32:8080/arcgis/rest/services/icm/icmRoomsAndBuildings/MapServer/0/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryPolygon&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json');
        $roomsJSON = json_decode($roomsJSON);  // Convert from JSON to PHP Object
        //print_r($roomsJSON); // Debugging.
        foreach($roomsJSON->features as $room) {
            $rooms_join_prefix = '';
            $building_join_previx = '';
            
            $attributes = objectToArray($room->attributes); // Convert to Arrays, because arrays are easier to read.
            //Uncomment the line below to print each output.
            //print_r($attributes); // Debug
            //  If there is no room number, we don't even want to bother importing it.
            if ($attributes[$rooms_join_prefix.'rm_num'] != '' && $attributes[$rooms_join_prefix.'rm_num'] != ' ' && $attributes[$rooms_join_prefix.'rm_num'] != null) {
                
                //Check if there is a building name attribute. 
                if($attributes[$rooms_join_prefix.'bl_name'] == '' || $attributes[$rooms_join_prefix.'bl_name'] == ' ' || $attributes[$rooms_join_prefix.'bl_name'] == null) {
                    // Try and get a building name by Querying the Building MapService                        
                    if($attributes[$building_join_prefix.'b_name'] == '' && $attributes[$building_join_prefix.'b_name'] == ' ' && $attributes[$building_join_prefix.'b_name'] == null) {
                        $label = 'Building #:'.$attributes[$rooms_join_prefix.'bl_id'].' Rm #: '.$attributes[$rooms_join_prefix.'rm_num'];
                    }
                    else {
                        $label = $attributes[$building_join_prefix.'b_name'].' Rm #: '.$attributes[$rooms_join_prefix.'rm_num'];
                    }
                    
                }
                else {
                    $label = $attributes[$rooms_join_prefix.'bl_name'].' '.$attributes[$rooms_join_prefix.'rm_num'];
                }
                $tags= '';
                //$tags.=trim($attributes[$rooms_join_prefix.'bl_id']).' ';
                $tags.=trim($attributes[$rooms_join_prefix.'bl_name']).' ';
                $tags.=trim($attributes[$rooms_join_prefix.'rm_num']).' ';
                $tags.=trim($attributes[$building_join_prefix.'b_name']).' ';
                $tags.=trim($attributes[$building_join_prefix.'b_abbreb']).' ';
                $tags.=str_replace('|',' ',$attributes[$rooms_join_prefix.'alt_identifiers']).' ';
                $tags.=str_replace('|',' ',$attributes[$building_join_prefix.'alt_identifiers']).' ';
                $tags = implode (' ', array_unique(explode(' ',$tags)));
                
                //$label = $room->attributes; 
                $geometry = str_replace('"', "", json_encode($room->geometry));
                
                //print('rooms|'.trim($label).'|'.trim(preg_replace('/( )+/', ' ', $tags)).'|'.trim($label).'|'.$geometry.'<br />');
                $array=array('category' => 'rooms','label' => trim($label), 'tags' => trim(preg_replace('/( )+/', ' ', $tags)), 'location' => trim($label), 'geometry' => $geometry);
                //print_r($array);
                $output[] = $array;
            }

        }
        // Clean and Prep the Database for insertion.
            if ($_GET['updateDB'] == 'yes') {
                $query = "DELETE FROM `searchablefeatures` WHERE `searchablefeatures`.`category` = 'rooms';";
                print($query.'<br />');
                if ($result = $mysqli->query($query)) {
                    print('Rooms features successfully cleared!<br />');
                }
                else {
                    print(mysqli_error($mysqli));
                }
                /* free result set */
                //$result->close(); 
            }
            // Setup the SQL statement with all the values.
            //print_r($output); // For Debugging only!
            foreach ($output as $building) {
                if ($_GET['updateDB'] == 'yes') {                  
                    //print_r($building);
                    $valuesSQL[]="('".mysqli_escape_string($mysqli, $building['category'])."', '".mysqli_escape_string($mysqli, $building['label'])."', '".mysqli_escape_string($mysqli, $building['tags'])."', '".mysqli_escape_string($mysqli, $building['location'])."', '".$building['geometry']."')";
                }
                else {
                    //print_r($building);
                    print($building['category'].'|'.$building['label'].'|'.$building['tags'].'|'.$building['location'].'|'.$building['geometry'].'<br />');
                }
            }
            // Insert values into Database.
            if ($_GET['updateDB'] == 'yes') {
                $values = implode(",\n", $valuesSQL);
                $query = "INSERT INTO `icm`.`searchablefeatures` (`category`, `label`, `tags`, `location`, `geometry`) VALUES ".$values.";";
                print ($query."\n");
                if ($result = $mysqli->query($query)) {
                    print("Insert Executed Successfully.");
                }
            }
        

     }
    if ($_GET['searchConfig'] == 'people') {
      print("People results are pulled directly from the UCSB Identity LDAP server and the user\'s location is cross referenced with our rooms dataset.<br /><br />Therefor there is no need to \"update\" the people searchable features...");
    }
    if($_GET['searchConfig'] == 'campusServices') {
                $output='';           
                $JSON = file_get_contents($layersConfig['resources']['url'].'/0/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=resource%2Croom%2Cb_name%2Croomnumber&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json');
                $JSON = json_decode($JSON);
                //print_r($JSON);
                foreach($JSON->features as $service) {
                    $services[]=$service;
                }
                $services = objectToArray($services);
                foreach($services as $service) {
                    //print_r($service);
                    $resource = explode('(',$service['attributes']['resource']);
                    $label = $resource[0];
                    $location = explode(')',$resource[1]);
                    $location = $location[0];
                    if ($location == '' || $location == null || $location == 'null') {
                        $location = $label;
                    }
                    $tags = $service['attributes']['resource'].' '.$service['attributes']['b_name'].' '.$service['attributes']['room'].' '.$service['attributes']['roomnumber'];
                    $tags = implode (' ', array_unique(explode(' ',$tags)));
                    //$output .= 'campusservice|'.trim($label).'|'.trim($tags).'|'.trim($location).'|'.json_encode($service['geometry']).'<br />';
                     $array=array('category' => 'campusservice','label' => mysqli_escape_string($mysqli, trim($label)), 'tags' => mysqli_escape_string($mysqli, trim($tags)), 'location' => mysqli_escape_string($mysqli, trim($label)), 'geometry' => str_replace('"', "", json_encode($service['geometry'])));
                    $output[] = $array;
                }
                //print $output;
                
            // Clean and Prep the Database for insertion.
            if ($_GET['updateDB'] == 'yes') {
                $query = "DELETE FROM `searchablefeatures` WHERE `searchablefeatures`.`category` = 'campusservice';";
                print($query.'<br />');
                if ($result = $mysqli->query($query)) {
                    print('Campus Services features successfully cleared!<br />');
                }
                else {
                    print(mysqli_error($mysqli));
                }
                /* free result set */
                //$result->close(); 
            }
            // Setup the SQL statement with all the values.
            foreach ($output as $building) {
                if ($_GET['updateDB'] == 'yes') {                  
                    //print_r($building);
                    $valuesSQL[]="('".mysqli_escape_string($mysqli, $building['category'])."', '".mysqli_escape_string($mysqli, $building['label'])."', '".mysqli_escape_string($mysqli, $building['tags'])."', '".mysqli_escape_string($mysqli, $building['location'])."', '".$building['geometry']."')";
                }
                else {
                    //print_r($building);
                    print($building['category'].'|'.$building['label'].'|'.$building['tags'].'|'.$building['location'].'|'.$building['geometry'].'<br />');
                }
            }
            // Insert values into Database.
            if ($_GET['updateDB'] == 'yes') {
                $values = implode(",\n", $valuesSQL);
                $query = "INSERT INTO `icm`.`searchablefeatures` (`category`, `label`, `tags`, `location`, `geometry`) VALUES ".$values.";";
                print ($query."\n");
                if ($result = $mysqli->query($query)) {
                    print("Insert Executed Successfully.");
                }
            }
                
        } // End Campus Services Search
        
if($_GET['searchConfig'] == 'recreationAreas') {
                $output='';           
                $JSON = file_get_contents($layersConfig['recreation']['url'].'/0/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json');
                $JSON = json_decode($JSON);
                //print_r($JSON);
                foreach($JSON->features as $service) {
                    $services[]=$service;
                }
                $services = objectToArray($services);
                foreach($services as $service) {
                    //print_r($service);
                    $label = $service['attributes']['name'];
                    $tags = $service['attributes']['name'].' '.$service['attributes']['type'];
                    $tags = implode (' ', array_unique(explode(' ',$tags)));
                    
                    $location = $service['attributes']['name'];
                    
                    //$output .= 'recreationarea|'.trim($label).'|'.trim($tags).'|'.trim($location).'|'.json_encode($service['geometry']).'<br />';
                    $array=array('category' => 'recreationarea','label' => mysqli_escape_string($mysqli, trim($label)), 'tags' => mysqli_escape_string($mysqli, trim($tags)), 'location' => mysqli_escape_string($mysqli, trim($location)), 'geometry' => str_replace('"', "", json_encode($service['geometry'])));
                    $output[] = $array;
                }
                //print $output;
            
            // Clean and Prep the Database for insertion.
            if ($_GET['updateDB'] == 'yes') {
                $query = "DELETE FROM `searchablefeatures` WHERE `searchablefeatures`.`category` = 'recreationarea';";
                print($query.'<br />');
                if ($result = $mysqli->query($query)) {
                    print('Campus Services features successfully cleared!<br />');
                }
                else {
                    print(mysqli_error($mysqli));
                }
                /* free result set */
                //$result->close(); 
            }
            // Setup the SQL statement with all the values.
            foreach ($output as $building) {
                if ($_GET['updateDB'] == 'yes') {                  
                    //print_r($building);
                    $valuesSQL[]="('".mysqli_escape_string($mysqli, $building['category'])."', '".mysqli_escape_string($mysqli, $building['label'])."', '".mysqli_escape_string($mysqli, $building['tags'])."', '".mysqli_escape_string($mysqli, $building['location'])."', '".$building['geometry']."')";
                }
                else {
                    //print_r($building);
                    print($building['category'].'|'.$building['label'].'|'.$building['tags'].'|'.$building['location'].'|'.$building['geometry'].'<br />');
                }
            }
            // Insert values into Database.
            if ($_GET['updateDB'] == 'yes') {
                $values = implode(",\n", $valuesSQL);
                $query = "INSERT INTO `icm`.`searchablefeatures` (`category`, `label`, `tags`, `location`, `geometry`) VALUES ".$values.";";
                print ($query."\n");
                if ($result = $mysqli->query($query)) {
                    print("Insert Executed Successfully.");
                }
            }
        } // End Campus Services Search
        
        
if($_GET['searchConfig'] == 'foodEstablishments') {
                $output='';           
                $JSON = file_get_contents($layersConfig['foodEstablishments']['url'].'/0/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=102100&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json');
                $JSON = json_decode($JSON);
                //print_r($JSON);
                foreach($JSON->features as $service) {
                    $services[]=$service;
                }
                $services = objectToArray($services);
                foreach($services as $service) {
                    //print_r($service);
                    $label = $service['attributes']['name'];
                    $location = $service['attributes']['address'];
                    
                    $delivery = '';
                    if ($service['attributes']['delivery'] == 'Y' || $service['attributes']['delivery'] == 'y') {
                        //print $service['attributes']['delivery'];
                        $delivery = 'delivery delivers';
                    }
                    $vegetarian = '';
                    if ($service['attributes']['vegetarian'] == 'Y' || $service['attributes']['vegetarian'] == 'y') {
                        //print $service['attributes']['vegetarian'];
                        $vegetarian = 'vegetarian';
                    }
                    $happyhour = '';
                    if ($service['attributes']['happy'] == 'Y' || $service['attributes']['happy'] == 'y') {
                        //print $service['attributes']['happy'];
                        $happyhour = 'happy hour';
                    }
                    $tags = $service['attributes']['name'].' '.$service['attributes']['category'].' '.$service['attributes']['category'].' '.$delivery.' '.$vegetarion.' '.$happyhour;
                    $tags = implode (' ', array_unique(explode(' ',$tags)));
                    
                    //$output .= 'foodestablishments|'.htmlspecialchars(trim($label)).'|'.htmlspecialchars(trim($tags)).'|'.htmlspecialchars(trim($location)).'|['.json_encode($service['geometry']).']<br />';
                    $array=array('category' => 'foodestablishments','label' => mysqli_escape_string($mysqli, htmlspecialchars(trim($label))), 'tags' => mysqli_escape_string($mysqli, htmlspecialchars(trim($tags))), 'location' => mysqli_escape_string($mysqli, htmlspecialchars(trim($location))), 'geometry' => '['.str_replace('"', "", json_encode($service['geometry'])).']');
                    $output[] = $array;                    
                }
                //print $output;
                
                // Clean and Prep the Database for insertion.
            if ($_GET['updateDB'] == 'yes') {
                $query = "DELETE FROM `searchablefeatures` WHERE `searchablefeatures`.`category` = 'foodestablishments';";
                print($query.'<br />');
                if ($result = $mysqli->query($query)) {
                    print('Food Establishment features successfully cleared!<br />');
                }
                else {
                    print(mysqli_error($mysqli));
                }
                /* free result set */
                //$result->close(); 
            }
            // Setup the SQL statement with all the values.
            foreach ($output as $building) {
                if ($_GET['updateDB'] == 'yes') {                  
                    //print_r($building);
                    $valuesSQL[]="('".mysqli_escape_string($mysqli, $building['category'])."', '".mysqli_escape_string($mysqli, $building['label'])."', '".mysqli_escape_string($mysqli, $building['tags'])."', '".mysqli_escape_string($mysqli, $building['location'])."', '".$building['geometry']."')";
                }
                else {
                    //print_r($building);
                    print($building['category'].'|'.$building['label'].'|'.$building['tags'].'|'.$building['location'].'|'.$building['geometry'].'<br />');
                }
            }
            // Insert values into Database.
            if ($_GET['updateDB'] == 'yes') {
                $values = implode(",\n", $valuesSQL);
                $query = "INSERT INTO `icm`.`searchablefeatures` (`category`, `label`, `tags`, `location`, `geometry`) VALUES ".$values.";";
                print ($query."\n");
                if ($result = $mysqli->query($query)) {
                    print("Insert Executed Successfully.");
                }
            }
                
                
        } // End Food Establishments Search
        if($_GET['searchConfig'] == 'parking') {
                $output='';           
                //This will get the layer ID# by searching through the list of layers looking for "All Parking Lots"
                //The parking layer must match the second parameter in order to be detected!
                
                $layerURL = $layersConfig['basemap']['url'];
                $layerID = getLayerIDbyName($layerURL,'All Parking Lots');
                $layerURL = $layerURL.'/'.$layerID.'/query?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=Number&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&f=json';
                print('<p>Query URL:<br />'. $layerURL .'</p>');
                $JSON = file_get_contents($layerURL);
                $JSON = json_decode($JSON);
                //print_r($JSON);
                foreach($JSON->features as $service) {
                    $services[]=$service;
                }
                $services = objectToArray($services);
                
                foreach($services as $service) {
                    if ($service['attributes']['lot_number'] != '' && $service['attributes']['lot_number'] != ' ' && $service['attributes']['lot_number'] != null) {
                        $tags = '';
                        //print_r($service);
                        $label = $service['attributes']['lot_number'];
                        $location = $service['attributes']['lot_number'];

                        if ($service['attributes']['reserved_parking'] == 'Yes' || $service['attributes']['reserved_parking'] == 'yes') {
                            $tags .= 'reserved ';
                        }
                        if ($service['attributes']['staff_parking'] == 'Yes' || $service['attributes']['staff_parking'] == 'yes') {
                            $tags .= 'staff ';
                        }
                        if ($service['attributes']['faculty_parking'] == 'Yes' || $service['attributes']['faculty_parking'] == 'yes') {
                            $tags .= 'faculty ';
                        }
                        if ($service['attributes']['resident_parking'] == 'Yes' || $service['attributes']['resident_parking'] == 'yes') {
                            $tags .= 'resident residential ';
                        }
                        if ($service['attributes']['vendor_parking'] == 'Yes' || $service['attributes']['vendor_parking'] == 'yes') {
                            $tags .= 'vendor ';
                        }
                        if ($service['attributes']['Metered_parking'] == 'Yes' || $service['attributes']['Metered_parking'] == 'yes') {
                            $tags .= 'metered meters ';
                        }
                        if ($service['attributes']['visitor_and_student_parking'] == 'Yes' || $service['attributes']['visitor_and_student_parking'] == 'yes') {
                            $tags .= 'visitor student ';
                        }
                        if ($service['attributes']['motorcycle_stalls'] == 'Yes' || $service['attributes']['motorcycle_stalls'] == 'yes') {
                            $tags .= 'motorcycle moto ';
                        }

                        $tags .= 'parking '.$service['attributes']['lot_number'];
                        $tags = implode (' ', array_unique(explode(' ',$tags)));

                        //print_r($service);
                        //$output .= 'parking|'.trim($label).'|'.trim($tags).'|'.trim($location).'|'.json_encode($service['geometry']).'<br />';
                        $array=array('category' => 'parking','label' => mysqli_real_escape_string($mysqli, trim($label)), 'tags' => mysqli_escape_string($mysqli, htmlspecialchars(trim($tags))), 'location' => mysqli_escape_string($mysqli, htmlspecialchars(trim($location))), 'geometry' => str_replace('"', "", json_encode($service['geometry'])));
                        $output[] = $array;          
                    }
                    
                }
                //print $output;
                
                
                    // Clean and Prep the Database for insertion.
            if ($_GET['updateDB'] == 'yes') {
                $query = "DELETE FROM `searchablefeatures` WHERE `searchablefeatures`.`category` = 'parking';";
                print($query.'<br />');
                if ($result = $mysqli->query($query)) {
                    print('Parking Lot features successfully cleared!<br />');
                }
                else {
                    print(mysqli_error($mysqli));
                }
                /* free result set */
                //$result->close(); 
            }
            // Setup the SQL statement with all the values.
            foreach ($output as $building) {
                if ($_GET['updateDB'] == 'yes') {                  
                    //print_r($building);
                    $valuesSQL[]="('".mysqli_escape_string($mysqli, $building['category'])."', '".mysqli_escape_string($mysqli, $building['label'])."', '".mysqli_escape_string($mysqli, $building['tags'])."', '".mysqli_escape_string($mysqli, $building['location'])."', '".$building['geometry']."')";
                }
                else {
                    //print_r($building);
                    print($building['category'].'|'.$building['label'].'|'.$building['tags'].'|'.$building['location'].'|'.$building['geometry'].'<br />');
                }
            }
            // Insert values into Database.
            if ($_GET['updateDB'] == 'yes') {
                $values = implode(",\n", $valuesSQL);
                $query = "INSERT INTO `icm`.`searchablefeatures` (`category`, `label`, `tags`, `location`, `geometry`) VALUES ".$values.";";
                print ($query."\n");
                if ($result = $mysqli->query($query)) {
                    print("Insert Executed Successfully.");
                }
            }
        } // End Parking Search
}  


$mysqli->close();
?>